/**
 * vuex 的简单对象模块
 */

/**
 * 在一个模块化的打包系统中，您必须显式地通过 Vue.use() 来安装 Vuex：
 */
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

/**
 * 导入常量
 */
import { DECREMENT_NUMBER, DECREMENT_BY_OBJ } from "./mutation-types";

/**
 * 创建一个 store
 */
const store = new Vuex.Store({
  state: {
    count: 0,
    name: "zxn",
    todos: [
      { id: 1, text: "吃早饭", done: true },
      { id: 2, text: "学习vue", done: true },
      { id: 3, text: "吃午饭", done: false },
    ],
  },
  getters: {
    count: (state) => {
      return state.count;
    },
    doneTodos: (state) => {
      return state.todos.filter((todo) => todo.done);
    },
    doneTodosCount: (state, getters) => {
      return getters.doneTodos.length;
    },
    getTodoById: (state) => (id) => {
      return state.todos.find((todo) => todo.id === id);
    },
    name: (state) => {
      return state.name;
    },
  },

  mutations: {
    increment(state) {
      state.count++;
    },
    incrementNumber(state, n) {
      state.count += n;
    },
    incrementByObj(state, payload) {
      state.count += payload.amount;
    },
    decrement(state) {
      state.count--;
    },
    [DECREMENT_NUMBER](state, n) {
      state.count -= n;
    },
    [DECREMENT_BY_OBJ](state, payload) {
      state.count -= payload.amount;
    },
    increment2(state) {
      state.count += 2;
    },
  },
  actions: {
    add5({ dispatch, commit }) {
      return dispatch("add6").then(() => {
        commit("decrement");
      });
    },
    add6({ commit }) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          commit("incrementNumber", 6);
          resolve();
        }, 1000);
      });
    },
    incrementNumber({ commit }, n) {
      setTimeout(() => {
        commit("incrementNumber", n);
      }, 1000);
    },
    incrementAsync2({ commit }, payload) {
      setTimeout(() => {
        commit("incrementByObj", payload);
      }, 1000);
    },
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit("increment");
      }, 1000);
    },
    decrement({ commit }) {
      commit("decrement");
    },
    increment(context) {
      context.commit("increment");
    },
  },
});

/**
 * 向外暴露store实例对象
 * 将该实例导出，以便在其他组件中使用该数据仓库
 */
export default store;
